<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2>登录 AirShare</h2>
        <p>文件分享与传输中心</p>
      </div>
      
      <!-- 登录方式切换 -->
      <div class="login-mode-switch">
        <el-radio-group v-model="loginMode" class="mode-radio-group">
          <el-radio-button label="password">密码登录</el-radio-button>
          <el-radio-button label="code">验证码登录</el-radio-button>
        </el-radio-group>
      </div>
      
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        label-width="0px"
        class="login-form"
      >
        <el-form-item prop="usernameOrEmail">
          <el-input
            v-model="loginForm.usernameOrEmail"
            type="text"
            :placeholder="loginMode === 'code' ? '邮箱地址' : '用户名或邮箱'"
            prefix-icon="User"
            size="large"
          />
        </el-form-item>
        
        <!-- 密码登录 -->
        <el-form-item v-if="loginMode === 'password'" prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="密码"
            prefix-icon="Lock"
            size="large"
            show-password
            @keyup.enter="handleLogin"
          />
        </el-form-item>
        
        <!-- 验证码登录 -->
        <template v-if="loginMode === 'code'">
          <el-form-item prop="verificationCode">
            <div class="verification-input">
              <el-input
                v-model="loginForm.verificationCode"
                type="text"
                placeholder="邮箱验证码"
                prefix-icon="Key"
                size="large"
                class="code-input"
                @keyup.enter="handleLogin"
              />
              <el-button
                type="primary"
                size="large"
                :disabled="!canSendCode || codeCountdown > 0"
                :loading="sendingCode"
                @click="sendVerificationCode"
                class="send-code-btn"
              >
                {{ getCodeButtonText }}
              </el-button>
            </div>
          </el-form-item>
        </template>
        
        <el-form-item>
          <el-button
            type="primary"
            size="large"
            :loading="loading"
            @click="handleLogin"
            class="login-btn"
          >
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
        
        <div class="login-footer">
          <router-link to="/register" class="register-link">
            还没有账号？立即注册
          </router-link>
        </div>
      </el-form>
      
    </div>
    
    <!-- ICP filing information -->
    <div class="icp-footer">
      <a href="https://beian.miit.gov.cn/" target="_blank">京ICP备18028985号-2</a>
    </div>
      
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Key } from '@element-plus/icons-vue'
import { login, loginWithCode } from '@/apis/user'
import { sendLoginVerificationCode } from '@/apis/user'
import { useUserStore } from '@/store/user'

const router = useRouter()
const userStore = useUserStore()

// 登录模式：password 或 code
const loginMode = ref('password')

// 表单数据
const loginForm = reactive({
  usernameOrEmail: '',
  password: '',
  verificationCode: ''
})

// 动态验证规则
const loginRules = computed(() => {
  const baseRules = {
    usernameOrEmail: [
      { required: true, message: loginMode.value === 'code' ? '请输入邮箱地址' : '请输入用户名或邮箱', trigger: 'blur' }
    ]
  }
  
  if (loginMode.value === 'password') {
    baseRules.password = [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6, message: '密码长度至少6位', trigger: 'blur' }
    ]
  } else {
    baseRules.verificationCode = [
      { required: true, message: '请输入验证码', trigger: 'blur' },
      { len: 6, message: '验证码为6位数字', trigger: 'blur' }
    ]
  }
  
  return baseRules
})

// 其他状态
const loading = ref(false)
const sendingCode = ref(false)
const codeCountdown = ref(0)
const loginFormRef = ref()

// 计算属性
const canSendCode = computed(() => {
  const email = loginForm.usernameOrEmail
  return email && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)
})

const getCodeButtonText = computed(() => {
  if (sendingCode.value) return '发送中...'
  if (codeCountdown.value > 0) return `${codeCountdown.value}s`
  return '发送验证码'
})

// 监听登录模式切换，清空表单
watch(loginMode, () => {
  loginForm.password = ''
  loginForm.verificationCode = ''
  // 重置表单验证状态
  if (loginFormRef.value) {
    loginFormRef.value.clearValidate()
  }
})

// 发送验证码（为已存在的用户发送登录验证码）
const sendVerificationCode = async () => {
  if (!canSendCode.value) {
    ElMessage.warning('请输入有效的邮箱地址')
    return
  }
  
  try {
    sendingCode.value = true
    
    // 使用专门的登录验证码接口
    const response = await sendLoginVerificationCode({ email: loginForm.usernameOrEmail })
    
    if (response.code === 200) {
      ElMessage.success('登录验证码已发送，请查收邮件')
      startCountdown()
    } else {
      ElMessage.error(response.message || '发送验证码失败')
    }
  } catch (error) {
    console.error('Send verification code error:', error)
    ElMessage.error('发送验证码失败，请稍后重试')
  } finally {
    sendingCode.value = false
  }
}

// 开始倒计时
const startCountdown = () => {
  codeCountdown.value = 60
  const timer = setInterval(() => {
    codeCountdown.value--
    if (codeCountdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  try {
    const valid = await loginFormRef.value.validate()
    if (!valid) return
    
    loading.value = true
    
    let response
    
    if (loginMode.value === 'password') {
      // 密码登录
      const loginData = {
        usernameOrEmail: loginForm.usernameOrEmail,
        password: loginForm.password
      }
      response = await login(loginData)
    } else {
      // 验证码登录
      const loginData = {
        email: loginForm.usernameOrEmail,
        verificationCode: loginForm.verificationCode
      }
      response = await loginWithCode(loginData)
    }
    
    if (response.code === 200) {
      // 存储用户信息到store
      userStore.setUserData(response.data)
      
      ElMessage.success('登录成功！')
      
      // 登录成功后跳转到首页或之前的页面
      const redirect = router.currentRoute.value.query.redirect || '/'
      router.push(redirect)
    } else {
      ElMessage.error(response.message || '登录失败')
    }
  } catch (error) {
    console.error('Login error:', error)
    if (loginMode.value === 'code') {
      ElMessage.error('验证码登录失败，请检查验证码是否正确')
    } else {
      ElMessage.error(error.message || '登录失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  box-sizing: border-box;
  margin: 0;
}

.login-box {
  width: 400px;
  max-width: 90vw;
  background: white;
  border-radius: 10px;
  padding: 40px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
  box-sizing: border-box;
}

.login-header {
  text-align: center;
  margin-bottom: 20px;
}

.login-mode-switch {
  margin-bottom: 25px;
  display: flex;
  justify-content: center;
}

.mode-radio-group {
  width: 100%;
  display: flex;
}

.mode-radio-group :deep(.el-radio-button) {
  flex: 1;
}

.mode-radio-group :deep(.el-radio-button__inner) {
  width: 100%;
  text-align: center;
  border-radius: 6px;
  padding: 12px 20px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.mode-radio-group :deep(.el-radio-button:first-child .el-radio-button__inner) {
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
  border-right: none;
}

.mode-radio-group :deep(.el-radio-button:last-child .el-radio-button__inner) {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}

.verification-input {
  display: flex;
  gap: 10px;
  align-items: stretch;
}

.code-input {
  flex: 1;
}

.code-input :deep(.el-input__wrapper) {
  height: 40px;
}

.send-code-btn {
  height: 40px;
  width: 110px;
  flex-shrink: 0;
  font-size: 13px;
  padding: 0 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.login-header h2 {
  color: #333;
  margin-bottom: 10px;
  font-size: 28px;
}

.login-header p {
  color: #666;
  font-size: 14px;
}

.login-form {
  width: 100%;
}

.login-btn {
  width: 100%;
  height: 45px;
  font-size: 16px;
  margin-top: 10px;
}

.login-footer {
  text-align: center;
  margin-top: 20px;
}

.register-link {
  color: #409eff;
  text-decoration: none;
  font-size: 14px;
}

.register-link:hover {
  text-decoration: underline;
}

.el-form-item {
  margin-bottom: 20px;
}

:deep(.el-input__wrapper) {
  padding: 12px 15px;
  height: 40px;
  box-sizing: border-box;
}

.icp-footer {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  text-align: center;
  z-index: 10;
}

.icp-footer a {
  color: rgba(255, 255, 255, 0.8);
  text-decoration: none;
  font-size: 12px;
  transition: color 0.3s ease;
}

.icp-footer a:hover {
  color: rgba(255, 255, 255, 1);
  text-decoration: underline;
}
</style>